package com.atguigu.spzx.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.vo.excel.ExcelCategoryVo;
import jakarta.annotation.Resource;
import jakarta.servlet.annotation.WebListener;
import org.springframework.beans.BeanUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author syh
 * @create 2023-08-21 18:24
 */

public class ExcelCategoryListener extends AnalysisEventListener<ExcelCategoryVo> {

    private List<Category> list=new ArrayList<>();
    private int limit=100;
    @Resource
    CategoryMapper categoryMapper;
    public ExcelCategoryListener(CategoryMapper categoryMapper){
        this.categoryMapper=categoryMapper;
    }

    @Override
    public void invoke(ExcelCategoryVo data, AnalysisContext analysisContext) {
        Category category=converExcelCategoryVo(data);
        if (category==null){
            return;
        }
        list.add(category);
        if (list.size()>=limit){
            //处理读取的数据转为category对象集合，过滤掉已存在的数据

            //批量保存
            categoryMapper.saveBatch(list);
            list.clear();
        }
    }
    //检查ExcelCategoryVo在数据库中是否已存在，不存在转为Category对象保存到数据库中
    private Category converExcelCategoryVo(ExcelCategoryVo data) {
        Long id = data.getId();
        Long parentId = data.getParentId();
        String name = data.getName();
        long count=categoryMapper.countByIdOrPidName(data);
        if (count>0){
            return null;
        }
        //转为Category
        Category category = new Category();
        BeanUtils.copyProperties(data,category);
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());

        return category;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (list.size()>0){
            //处理读取的数据转为category对象集合，过滤掉已存在的数据

            //批量保存
            categoryMapper.saveBatch(list);
            list.clear();
        }
    }
}
